package com.zhangyang.netty.register;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ASUS on 2017/9/24.
 */
public class RegisterHandler extends ChannelInboundHandlerAdapter{

    //对应的hashmap
    private ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<String, Object>();

    //保存对应的扫描路径下名称
    private List<String> cacheList=new ArrayList<String>();

    //com.zhangyang.netty.provider
    public RegisterHandler(){
        scanClass("com.zhangyang.netty.provider");
        doRegister();
    }
    /**
     * 读取的一些信息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("RegisterHandler ....channelRead....");
        //进行读取到对象
        Object result=new Object();
        InvokerMsg invokerMsg=(InvokerMsg)msg;

        //进行从map集合中获取
        if(concurrentHashMap.containsKey(((InvokerMsg) invokerMsg).getClassName())){
            System.out.println("RegisterHandler ....channelRead....1111111111:"+invokerMsg.getClassName());
            //如果包含
            Object object1 = concurrentHashMap.get(invokerMsg.getClassName());
            Method method = object1.getClass().getMethod(invokerMsg.getMethodName(), invokerMsg.getParams());
            result = method.invoke(object1, invokerMsg.getValues());
            ctx.writeAndFlush(result);
            ctx.close();
        }else{
            System.out.println("RegisterHandler ....channelRead....22222222222");
            ctx.close();
        }
    }

    /**
     * 异常的捕获
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 扫描对应路径下文件
     * @param packageName
     */
    private void scanClass(String packageName){
        System.out.println("scanClass packageName:"+packageName+"..."+packageName.replace(".", "/"));
        //获取文件资源
        URL url = this.getClass().getClassLoader().//
                getResource(packageName.replace(".", "/"));
        System.out.println("url is null:"+(url==null)+"....url.getFile():"+url.getFile());
        File fileDir=new File(url.getFile());
        for (File file : fileDir.listFiles()) {
            //进行遍历 文件集合
            if(file.isDirectory()){
                //如果是目录
                scanClass(packageName+"."+file.getName());
            }else{
                //如果是文件
                String className = packageName+"."+file.getName().replace(".class", "");
                cacheList.add(className);
            }
        }
    }

    /**
     * 进行注册
     */
    private void doRegister(){

        System.out.println("cacheList:"+cacheList.toString());
        //进行遍历集合
       for(String clazzName:cacheList){
           try {
               Class<?> clazz=Class.forName(clazzName);
               Class<?> interfaces=clazz.getInterfaces()[0];
               System.out.println("interfaces.getName():"+interfaces.getName());
               concurrentHashMap.put(interfaces.getName(),clazz.newInstance());
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
    }
}
